package edu.sjb.gui;

import java.awt.event.KeyEvent;
import java.awt.event.KeyListener;

import edu.sjb.characters.Mario;

public class GameScreenKeyListener implements KeyListener {
	protected boolean leftKeyPushed;
	protected boolean rightKeyPushed;
	protected boolean jumpKeyPushed;
	protected boolean runKeyPushed;
	protected Mario mario;

	public GameScreenKeyListener(Mario miMario) {
		this.mario = miMario;
	}

	@Override
	public void keyPressed(KeyEvent evt) {

		if (evt.getKeyCode() == KeyEvent.VK_RIGHT) {
			if (!rightKeyPushed) {
				rightKeyPushed = true;
			}
		}
		else {
			if (evt.getKeyCode() == KeyEvent.VK_LEFT) {
				if (!leftKeyPushed) {
					leftKeyPushed = true;
				}
			}
			else {
				if (evt.getKeyCode() == KeyEvent.VK_X) {
					if (!jumpKeyPushed && mario.canJump()) {
						jumpKeyPushed = true;
					}
				}
				else {
					if (evt.getKeyCode() == KeyEvent.VK_Z) {
						if (!runKeyPushed) {
							if (mario.underFlowerEffect()) {
								runKeyPushed = true;
								mario.action2();
							}
							else {
								if (rightKeyPushed || leftKeyPushed) {
									runKeyPushed = true;
									mario.dash();
								}
							}
						}
					}
				}
			}
		}
	}

	@Override
	public void keyReleased(KeyEvent evt) {

		if (evt.getKeyCode() == KeyEvent.VK_RIGHT) {
			if (rightKeyPushed) {
				rightKeyPushed = false;
				mario.stopRight();

			}
		}
		else {
			if (evt.getKeyCode() == KeyEvent.VK_LEFT) {
				if (leftKeyPushed) {
					leftKeyPushed = false;
					mario.stopLeft();

				}
			}
			else {
				if (evt.getKeyCode() == KeyEvent.VK_X) {
					if (jumpKeyPushed) {
						jumpKeyPushed = false;
					}
				}
				else {
					if (evt.getKeyCode() == KeyEvent.VK_Z) {
						if (runKeyPushed) {
							runKeyPushed = false;
							if (!mario.underFlowerEffect()) {
								mario.dash();
							}
						}
					}
				}
			}
		}
	}

	@Override
	public void keyTyped(KeyEvent evt) {
	}

	public boolean canRun() {
		return runKeyPushed;
	}

	public boolean canJump() {
		return jumpKeyPushed && mario.canJump();
	}

	public boolean canMoveRight() {

		boolean possible = rightKeyPushed && mario.canGoRight();
		if (possible && !mario.canGoLeft()) {
			mario.setCanGoLeft(true);
		}
		return possible;
	}

	public boolean canMoveLeft() {
		boolean possible = leftKeyPushed && mario.canGoLeft();
		if (possible && !mario.canGoRight()) {
			mario.setCanGoRight(true);
		}
		return possible;
	}
}
